package com.lange.fileManagement.service;

import com.alibaba.fastjson.JSONObject;
import com.lange.fileManagement.dao.UserDaoImpl;
import com.lange.fileManagement.utils.Result;
import com.lange.fileManagement.utils.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDaoImpl userDaoImpl;

    /*添加用户*/
    @Transactional
    public Integer addUser(JSONObject data) {
        try {
            if (data.getInteger("role") == 1 && hadAdmin()) {  // 注册管理员,然而已存在管理员
                return 101;
            }
            // 判断是否存在相同用户名
            String username = data.getString("username");
            String sql = "username='" + username + "'";
            List<JSONObject> users = userDaoImpl.getUser(sql);
            if (users.isEmpty()) {
                return userDaoImpl.addUser(data);
            }
            return 102;  // 存在相同用户名
        } catch (Exception e) {
            e.printStackTrace();
            return 500;
        }
    }

    /*检测是否存在管理员*/
    public boolean hadAdmin() {
        try {
            List<JSONObject> userByRole = userDaoImpl.getUserByRole("1");
            return !userByRole.isEmpty();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /*获取个人信息*/
    public JSONObject getMyInfo(String token) {
        if (token == null) {
            return null;
        }
        try {
            String sql = "token_value='" + token + "'";
            JSONObject tokenObj = userDaoImpl.getToken(sql);
            Integer userId = tokenObj.getInteger("user_id");
            String sql2 = "user_id=" + userId;
            List<JSONObject> users = userDaoImpl.getUser(sql2);
            users.forEach(user -> {
                user.remove("password");  // 移除密码字段
            });
            return users.isEmpty() ? null : users.get(0);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*找回密码*/
    @Transactional
    public Integer findPassword(JSONObject data) {
        try {
            // 根据用户名和密保查找用户
            String sql = "username='" + data.getString("username") + "' AND secret='"
                    + data.getString("secret") + "'";
            List<JSONObject> users = userDaoImpl.getUser(sql);
            if (users.isEmpty()) {   // 用户名或者密保不正确
                return 100;
            }
            // 重置密码
            Integer i = userDaoImpl.setPassword(data);
            if (i == 1)
                return 0;
            else
                return 101;
        } catch (Exception e) {
            e.printStackTrace();
            return 101;
        }
    }

    // 登录，并更新token
    @Transactional
    public JSONObject login(JSONObject data) {
        JSONObject res = new JSONObject();
        try {
            // 根据用户名和密保查找用户
            String sql = "username='" + data.getString("username") + "' AND password='"
                    + data.getString("password") + "'";
            List<JSONObject> users = userDaoImpl.getUser(sql);
            if (users.isEmpty()) {   // 用户名或密码错误
                res.put("code", 100);
                return res;
            }
            // 删除旧的token
            Integer userId = users.get(0).getInteger("id");
            res.put("userId", userId);
            userDaoImpl.delToken(res);
            res.remove("userId");
            // 生成token
            String token = TokenGenerator.generateToken(32);
            res.put("code", 0);
            res.put("token", token);
            // 插入Token
            JSONObject data2 = new JSONObject();
            data2.put("userId", userId);
            data2.put("tokenValue", token);
            userDaoImpl.addToken(data2);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 101);
            return res;
        }
    }

    // 校验Token是否过期
    @Transactional
    public Result checkToken(String token) {
        try {
            // 查询Token
            String sql = "token_value='" + token + "' AND created > NOW() - INTERVAL 7 DAY";
            JSONObject tokenObj = userDaoImpl.getToken(sql);
            System.out.println(tokenObj);
            if (tokenObj == null) {   // 用户名或密码错误
                return Result.error("100", "token不存在或过期");
            }
            // 删除旧的token
            JSONObject data = new JSONObject();
            data.put("tokenValue", token);
            userDaoImpl.delToken(data);
            // 生成token
            String tokenNew = TokenGenerator.generateToken(32);
            // 插入Token
            JSONObject data2 = new JSONObject();
            data2.put("userId", tokenObj.getInteger("user_id"));
            data2.put("tokenValue", tokenNew);
            userDaoImpl.addToken(data2);
            return Result.success(tokenNew);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("101", "系统异常");
        }
    }

}
